#!/bin/bash

# SPAM3UK 快速修复部署脚本
# 专门用于修复HTTP/2连接问题

echo "🚀 SPAM3UK 快速修复部署"
echo "========================"
echo "修复: HTTP/2 stream error 问题"
echo "开始时间: $(date)"
echo ""

# 检查当前位置
echo "📍 当前工作目录: $(pwd)"

# 1. 停止服务
echo "1️⃣ 停止当前服务..."
sudo pkill -f spam3uk 2>/dev/null || echo "  没有运行的spam3uk进程"
sudo pkill -f "go run" 2>/dev/null || echo "  没有运行的go进程"
sleep 2

# 2. 备份并清理
echo ""
echo "2️⃣ 清理环境..."
if [ -d "spam3uk" ]; then
    echo "  发现现有spam3uk目录，重命名为备份"
    mv spam3uk spam3uk.backup.$(date +%Y%m%d_%H%M%S)
fi

# 3. 重新克隆最新代码
echo ""
echo "3️⃣ 获取最新代码..."
git clone https://gitee.com/andershsueh/spam3uk.git
if [ $? -ne 0 ]; then
    echo "  ❌ 代码克隆失败"
    exit 1
fi

echo "  ✅ 代码克隆完成"

# 4. 进入项目目录
cd spam3uk || { echo "❌ 无法进入spam3uk目录"; exit 1; }
echo "  📂 进入项目目录: $(pwd)"

# 5. 替换配置文件
echo ""
echo "4️⃣ 配置服务器设置..."
if [ -f "../spam3uk-config.json" ]; then
    cp ../spam3uk-config.json ./spam3uk-config.json
    echo "  ✅ 配置文件已更新"
else
    echo "  ⚠️ 未找到服务器配置文件，使用默认配置"
fi

# 6. 验证关键修复
echo ""
echo "5️⃣ 验证HTTP/2修复..."
if grep -q "ForceAttemptHTTP2.*false" internal/scraper/vehicle_scraper.go; then
    echo "  ✅ HTTP/2禁用配置: 已找到"
else
    echo "  ❌ HTTP/2禁用配置: 缺失"
fi

if grep -q 'req.Proto = "HTTP/1.1"' internal/scraper/vehicle_scraper.go; then
    echo "  ✅ HTTP/1.1强制配置: 已找到"
else
    echo "  ❌ HTTP/1.1强制配置: 缺失"
fi

if grep -q '"host": "0.0.0.0"' spam3uk-config.json; then
    echo "  ✅ 外部访问配置: 正确"
else
    echo "  ❌ 外部访问配置: 错误"
fi

# 7. 编译服务
echo ""
echo "6️⃣ 编译服务..."
go mod tidy
go build -o spam3uk main.go
if [ $? -eq 0 ]; then
    echo "  ✅ 编译成功"
    ls -la spam3uk
else
    echo "  ❌ 编译失败"
    echo "  📋 Go版本信息:"
    go version
    exit 1
fi

# 8. 启动服务
echo ""
echo "7️⃣ 启动服务..."
chmod +x spam3uk
nohup ./spam3uk > server.log 2>&1 &
PID=$!
echo "  ✅ 服务已启动 (PID: $PID)"

# 9. 等待并检查
echo ""
echo "8️⃣ 服务健康检查..."
sleep 5

for i in {1..8}; do
    if curl -s http://localhost:5700/health > /dev/null 2>&1; then
        echo "  ✅ 服务运行正常!"
        echo "  📊 健康状态:"
        curl -s http://localhost:5700/health | jq . 2>/dev/null || curl -s http://localhost:5700/health
        break
    else
        echo "  ⏳ 等待服务启动... ($i/8)"
        sleep 3
    fi
    
    if [ $i -eq 8 ]; then
        echo "  ❌ 服务启动失败!"
        echo "  📋 错误日志:"
        tail -20 server.log
        exit 1
    fi
done

# 10. 测试修复
echo ""
echo "9️⃣ 测试HTTP/2修复..."
echo "  🧪 执行抓取测试 (应该不再出现stream error)..."
timeout 30 curl -X POST http://localhost:5700/api/scrape_all
CURL_EXIT=$?

if [ $CURL_EXIT -eq 0 ]; then
    echo "  ✅ 抓取API执行完成!"
elif [ $CURL_EXIT -eq 124 ]; then
    echo "  ⏰ 抓取超时 (正常，说明没有立即失败)"
else
    echo "  ⚠️ 抓取API返回状态: $CURL_EXIT"
fi

echo ""
echo "  📋 检查最新日志 (查找是否还有stream error):"
tail -10 server.log | grep -E "(error|Error|stream|INTERNAL)" || echo "  ✅ 未发现stream error!"

# 完成
echo ""
echo "🎉 部署完成!"
echo "===================="
echo "服务地址: http://$(hostname -I | awk '{print $1}'):5700"
echo "外部访问: http://101.201.32.200:5700"
echo "健康检查: curl http://localhost:5700/health"
echo "完成时间: $(date)"
echo ""
echo "🔧 快速测试命令:"
echo "curl -X POST http://101.201.32.200:5700/api/scrape_all"
echo "tail -f server.log"
